<template>
	<view class="coupons" :style="{height:screenHeight+'px'}">
		<uni-segmented-control @clickItem="onClickItem" styleType="text" :values="list" activeColor="#ff557f"> </uni-segmented-control>
		<view v-show="current === 0" class="tab">
			<lgf-coupon :coupons="coupons" @getCoupon="getCoupon"></lgf-coupon>
		</view>
		<view v-show="current === 1" class="tab">
			<lgf-coupon :coupons="personCoupons" @getCoupon="getCoupon"></lgf-coupon>
		</view>

	</view>
</template>

<script>
	import lgfCoupon from '../../components/lgf-coupon/lgf-coupon.vue'
	import moment from 'moment'
	export default {
		data() {
			return {
				screenHeight: '',
				coupons: [],
				current: 0,
				list: ['领取优惠卷', '我的']
			}
		},
		onLoad() {
			this.screenHeight = uni.getSystemInfoSync().windowHeight
			this.getCoupons()
			this.getPersonCoupon()
		},
		computed:{
			personCoupons(){
				return this.$store.state.m_user.coupons
			}
		},
		components: {
			lgfCoupon
		},
		methods: {
			onClickItem(e) {
				this.current = e.currentIndex;
				// console.log(e)
			},
			// 领取优惠卷
			getCoupon(item){
				uni.$http.get(`/coupon-server/api/coupon/v1/add/promotion/${item.id}`).then(res=>{
					// console.log(res)
					if(res.data.code===200){
						uni.$showMsg('领取成功')
						// this.getPersonCoupon()
					}else if(res.data.msg==='优惠券库存不足'){
						uni.$showMsg('优惠券库存不足')
					}else if(res.data.msg==='优惠券领取超过限制次数'){
						uni.$showMsg('你已经领完了！')
					}else{
						uni.$showMsg('领取失败')
					}
				})
			},
			//查询个人优惠卷
			getPersonCoupon(){
				uni.$http.get(`/coupon-server/api/coupon_record/v1/page?page=1&size=10`).then(res=>{
					this.$store.commit('m_user/updateCoupons',res.data.data.current_data)
					// console.log(this.personCoupons)
				})
			},
			getCoupons() {
				uni.$http.get('/coupon-server/api/coupon/v1/page_coupon?page=1&size=10').then(res => {
					// console.log(res)
					let data = res.data.data
					let current_data = data.current_data
					current_data.forEach(item => {
						item.state = this.guoqi(item.end_time)
					})
					this.coupons = current_data
					// console.log(this.coupons)
				})
			},
			guoqi(time) {
				let m1 = moment(time),
					m2 = moment();
				if (m2.diff(m1, 'minute') >= 0) {
					return true
				} else {
					return false
				}
			}
		}
	}
</script>

<style scoped>
	.coupons {
		position: fixed;
		left: 0;
		right: 0;
		background-image: linear-gradient(180deg, #FFFFFF 0%, #ff557f 50%, #c44163 100%);
		overflow: auto;
	}
</style>
